﻿using Microsoft.AspNetCore.Mvc;
using slwhTools.SLog;
using System.Net;
using System.Text;
using System;
using Newtonsoft.Json;
using OfficeOpenXml;
using System.ComponentModel.DataAnnotations.Schema;
using slwhTools.ExcelHelper;
using NPOI.XSSF.UserModel;
using NPOI.OpenXml4Net.OPC.Internal;
using slwhTools.FileHelper;

namespace ceshiapi.Controllers
{

    [ApiController]
    [Route("[controller]")]
    public class CeshiController : Controller
    {
        //注册日志依赖
        private readonly ISLogService<CeshiController> slog;



        public CeshiController(ISLogService<CeshiController> _slog)
        {
            slog = _slog;
        }

        [HttpGet("Index")]
        public IActionResult Index()
        {
            slog.LogInformation("info");
            slog.LogError("error");
            return Json("");
        }

        [HttpGet("Index1")]
        public IActionResult Index1()
        {
            string resultstr = string.Empty;
            var url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww3d4303fc8d2a03a9&corpsecret=XrfpBhOxTX61XyqaJJB-nOjQ8XDQEYYPsnr7ZSSVYm4";
            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            req.Method = "GET";

            System.Net.WebResponse rep = req.GetResponse();
            Stream getStream = rep.GetResponseStream();
            using (StreamReader sr = new StreamReader(getStream, Encoding.UTF8))
            {
                resultstr = sr.ReadToEndAsync().Result;
                sr.Close();
            }
            getStream.Close();

            rep.Close();

            return Json(resultstr);
        }

        [HttpPost("upload")]
        public ActionResult<List<Employee>> ImportExcel()
        {
            try
            {
                // 检查请求是否包含文件
                if (Request.Form.Files.Count == 0)
                    return BadRequest("No file uploaded.");

                var file = Request.Form.Files[0];

                // 检查文件扩展名
                var extension = Path.GetExtension(file.FileName).ToLower();
                if (extension != ".xlsx" && extension != ".xls")
                    return BadRequest("Only Excel files are allowed.");


                // 读取Excel文件
                var employees = new List<Employee>();
                using (var stream = new MemoryStream())
                {
                    file.CopyToAsync(stream);

                    var list = stream.ReadExcel<Employee>();
                }

                return Ok(employees);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Internal server error: {ex.Message}");
            }
        }

        [HttpPost("import")]
        public ActionResult ImportExcelFile()
        {
            var list = new List<Employee>();
            var mod = new Employee();
            mod.Id = "1111";
            mod.Name = "姓名";
            mod.Sex = "男";
            for (int i = 0; i < 2000; i++)
            {
                list.Add(mod);
            }

            ISExcel.type = WorkType.SXLSX;

            list.ImportExcel();
            ISExcel.sheet = ISExcel.workbook.CreateSheet("测试");
            list.ImportExcel();

            SExcelExtensions.sexcel.SExcelInit();

            var s = ISExcel.workbook.ImportExcelStream();

            
            return File(s.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "UsersExport.xlsx");

        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <returns></returns>
        [HttpPost("SavaFile")]
        public ActionResult SavaFile(IFormFile file) {
            var msg = file.SaveFile();

            return Ok(msg);
        }

    }


    public class Employee
    {
        [SColumn("编号")]
        public string Id { get; set; }
        [SColumn("姓名")]
        public string Name { get; set; }
        [SColumn("性别")]
        public string Sex { get; set; }
    }


    public class QyWechatUserRequest
    {
        /// <summary>
        /// 手机号
        /// </summary>
        public string Code { get; set; }
    }

    public class QyWechatUserResponse
    {
        /// <summary>
        /// 错误code
        /// </summary>
        [JsonProperty("errcode")]
        public int ErrCode { get; set; }

        /// <summary>
        /// 错误提示
        /// </summary>
        [JsonProperty("errmsg")]
        public string ErrMsg { get; set; }

        /// <summary>
        /// 企业用户
        /// </summary>
        [JsonProperty("userid")]
        public string UserId { get; set; }

        /// <summary>
        /// 企业用户
        /// </summary>
        [JsonProperty("user_ticket")]
        public string UserTicket { get; set; }

        /// <summary>
        /// 非企业用户
        /// </summary>
        [JsonProperty("openid")]
        public string OpenId { get; set; }

        /// <summary>
        /// 非企业用户
        /// </summary>
        [JsonProperty("external_userid")]
        public string ExternalUserId { get; set; }
    }

    public class WechatTokenResponse
    {
        /// <summary>
        /// 错误code
        /// </summary>
        [JsonProperty("errcode")]
        public int ErrCode { get; set; }

        /// <summary>
        /// 错误提示
        /// </summary>
        [JsonProperty("errmsg")]
        public string ErrMsg { get; set; }

        /// <summary>
        /// token
        /// </summary>
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }

        /// <summary>
        /// 耗时事件
        /// </summary>
        [JsonProperty("expires_in")]
        public int ExpiresIn { get; set; }
    }
}
